package com.cacho.s2b.lesson.grammar.func;

import com.cacho.s2b.lesson.security.Activation;
import com.cacho.s2b.lesson.security.EncryptHelper;
import com.cacho.s2b.lesson.vo.ApiTestInfo;
import com.nimbusds.jose.*;
import com.nimbusds.jose.crypto.RSASSASigner;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class GrammarFuncJWS implements GrammarFunc {
    @Override
    public String getString(ApiTestInfo testInfo, String[] parts, int len) {
        int paramSize = parts.length;
        if (paramSize < 1) {
            return null;
        }
        // groupId 必填
        String groupId = parts[0];
        String privateKey = Activation.loadActivationProps().getProperty(groupId + "_PrivateKey");
        String payload = testInfo.getLastStepInfo().getRequest().getBody();
        String jws = "";
        if (payload != null) {
            try {
                JWSSigner signer = new RSASSASigner(new EncryptHelper().StringToPrivateKey(privateKey));
                JWSObject jwsObject = new JWSObject(new JWSHeader.Builder(JWSAlgorithm.RS256).
                        type(JOSEObjectType.JWT).build(), new Payload(payload));
                jwsObject.sign(signer);
                String[] splitString = jwsObject.serialize().split("\\.");
                log.info("JWS完整数据：{}", jwsObject.serialize());
                jws = splitString[0] + ".." + splitString[2];
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return jws;
    }
}
